package dmwr.web;

import dmwr.Dmwr;
import dmwr.bean.Entry;
import dmwr.service.Service.Duplicate;

public class EntryAdmin {

	private static final int PAGE_SIZE = 15;

	public void list() {
		String page = Http.request().getParameter("page");
		int pageNum = page != null && page.length() > 0 ? Integer
				.parseInt(page) : 1;
		Http.request().setAttribute("page",
				Dmwr.service().listEntries(pageNum, PAGE_SIZE));
		Http.forward("/admin/entry/list.jsp");
	}

	public void add() {
		form();
	}

	public void edit() {
		Http.request().setAttribute(
				"item",
				Dmwr.service().getEntry(
						Long.parseLong(Http.request().getParameter("id"))));
		form();
	}

	private void form() {
		Http.request().setAttribute("pools",
				Dmwr.service().listPools(1, 100).getItems());
		Http.forward("/admin/entry/form.jsp");
	}

	public void save() {
		Long id = Http.request().getParameter("id") != null ? Long
				.parseLong(Http.request().getParameter("id")) : null;
		Entry entry = new Entry(id, Long.parseLong(Http.request().getParameter(
				"poolId")), Http.request().getParameter("text1"), Http
				.request().getParameter("text2"), null);
		try {
			Dmwr.service().saveEntry(entry);
			Http.redirect("/admin/entry");
		} catch (Duplicate e) {
			Http.redirect("/admin/entry?edit=&id="
					+ ((Entry) e.getExisting()).getId());
		}
	}

	public void delete() {
		Dmwr.service().deleteEntry(
				Long.parseLong(Http.request().getParameter("id")));
		Http.redirect("/admin/entry");
	}
}